#include "Logger.h"
#include "LogRecorder.h"
#include <iostream>

Logger& Logger::getInstance()
{
	static Logger instance;
	return instance;
}

Logger::Logger()
{

}

Logger::~Logger()
{
	this->stop();
}

bool Logger::start()
{
	this->mShutdownFlag = false;
	this->mWorkerThread = std::thread(&Logger::run, this);//开启单消费线程
	return true;
}

void Logger::doWrite(LogLevel level, const std::string& log, const std::string& file, int line)
{
	do
	{
		std::lock_guard<std::mutex> lock(mQueueMutex);
		LogInfo loginfo(level, log, file, line);
		mTaskQueue.emplace(loginfo);
	} while (0);
	mCv.notify_one();
}

void Logger::addLogRecorder(LogRecorderPtr logrecorder)
{
	this->mLogRecordList.push_back(logrecorder);
}

void Logger::delLogRecorder(LogRecorderPtr logrecorder)
{
	this->mLogRecordList.remove(logrecorder);
}

void Logger::stop()
{
	//退工作线程
	do
	{
		std::lock_guard<std::mutex> lock(mQueueMutex);
		this->mShutdownFlag = true;
	} while (0);
	mCv.notify_all();
	if (mWorkerThread.joinable())
		mWorkerThread.join();
}

void Logger::run()
{
	while (true)
	{
		std::unique_lock<std::mutex> lock(mQueueMutex);
		// 等待队列非空或关闭信号
		mCv.wait(lock, [this]() { 
			return !mTaskQueue.empty() || mShutdownFlag; 
			});

		if (mShutdownFlag && mTaskQueue.empty()) 
		{
			break; // 优雅退出条件：要求关闭且队列已空
		}

		if (!mTaskQueue.empty()) 
		{
			LogInfo task = std::move(mTaskQueue.front());
			mTaskQueue.pop();
			lock.unlock(); // 取出任务后尽早释放锁

			// 在此线程中同步通知所有观察者
			for (auto& logrecorder : mLogRecordList) 
			{
				// 调用每个日志器的写入接口
				logrecorder->doWrite(task.level, task.log, task.file, task.line); 
			}
		}
	}
}
